#include "newfile.h"

Newfile::Newfile(QWidget * parent, const QString & f, const int h,const int w){
	setFixedSize(w,h);
	if (f != NULL){
		title = new QLineEdit(f);
		text = new QTextEdit();
		QFile data(f);
		if (data.open(QFile::ReadOnly)){
			QTextStream fin(&data);
			fin.setCodec("UTF-8");
			//fin.setAutoDetectUnicode(true);
			text->setText(fin.readAll());
			data.close();
		}
	}else {
		title = new QLineEdit();
		text = new QTextEdit();
	}
	QVBoxLayout * main = new QVBoxLayout;
	QHBoxLayout * btns = new QHBoxLayout;
	save = new QPushButton("Save");
	cancel = new QPushButton("Cancel");
	btns->addWidget(save);
	btns->addWidget(cancel);
	main->addWidget(title);
	main->addWidget(text);
	main->addLayout(btns);
	setLayout(main);
	
	QObject::connect(save,SIGNAL(clicked()),this,SLOT(saveAndClose()));
	QObject::connect(cancel,SIGNAL(clicked()),this,SLOT(hide()));
}
void Newfile::reset(){title->setText(""); text->setText("");}
void Newfile::saveAndClose(){
	QFile data(QString("%1.%2").arg(title->text()).arg("txt"));
	if (data.open(QFile::WriteOnly)){
		QTextStream fout(&data);
		fout.setCodec("UTF-8");
		fout << text->toPlainText();
		fout.flush();
		emit savedSth();
		data.close();
	}
	hide();
}
void Newfile::fromFile(const QString & f){
	QFile data(QString("%1.%2").arg(f).arg("txt"));
	if (data.exists()){
		title->setText(f);
		if (data.open(QFile::ReadOnly)){
			QTextStream fin(&data);
			fin.setCodec("UTF-8");
			//fin.setAutoDetectUnicode(true);
			text->setText(fin.readAll());
		}else text->setText("No such entry");
		data.close();
	}
}
void Newfile::deleteEntry(const QString & f){
QFile data(QString("%1.%2").arg(f).arg("txt"));
if (data.exists()){ data.remove(); emit savedSth();}
}
